import requests
import re

# 方式一 手动
# headers = {
# 	"cookie": "session=eyJjc3JmX3Rva2VuIjoiZEx5elVjRGtKSEdmYVpOUXN0UHJuQW1YamxxVFlCUk1vaGlFd1NnYktJRnB2eHVXQ2VWTyIsInVzZXJuYW1lIjoiYWRtaW4ifQ.Z-ziaA.-o-hG9o6zmXnwGtUD5AY9-hZ6DE"
# }
# res = requests.get("https://quotes.toscrape.com/", headers=headers)
# state = re.search(r'<div class="col-md-4">.*?<a href=".*?">(.*?)</a>', res.text, re.S)
# print(state.group(1))

# 方式二 session
# session = requests.Session()
# print(session.cookies)
#
# session.post("https://quotes.toscrape.com/login", data={
# 	"username": "admin",
# 	"password": "12345"
# }, allow_redirects=False)
# print(session.cookies)
#
# res = session.get("https://quotes.toscrape.com/")
# state = re.search(r'<div class="col-md-4">.*?<a href=".*?">(.*?)</a>', res.text, re.S)
# print(state.group(1))

# 1. 想登录页面发起get请求  获取csrf_token 以及cookie
login_get_res = requests.get("https://quotes.toscrape.com/login")
print("发起get请求获取cookie", login_get_res.cookies)

csrf_token_text = re.search(r'<input type="hidden" name="csrf_token" value="(.*?)"/>', login_get_res.text, re.S)
if csrf_token_text:
    csrf_token = csrf_token_text.group(1)
    # 2. 发post请求 携带cookie与csrf_token
    login_post_res = requests.post("https://quotes.toscrape.com/login", data={
        "csrf_token": csrf_token,
        "username": "admin",
        "password": "123456"
    }, cookies=login_get_res.cookies, allow_redirects=False)
    print("发起post请求获取cookie", login_post_res.cookies)
    res = requests.get("https://quotes.toscrape.com/", cookies=login_post_res.cookies)
    state = re.search(r'<div class="col-md-4">.*?<a href=".*?">(.*?)</a>', res.text, re.S)
    print(state.group(1))
